<?php
/*
	Laborator Image Resizer for WordPress
	
	Developed by: Arlind Nushi
	Website: www.arlindnushi.com & www.laborator.co
	
	Note: Zebra_Image class is required in order this plugin to work.
	Visit {@link http://stefangabos.ro/php-libraries/zebra-image/} to download this class and include on your file.
*/

# include_once('Zebra_Image.php'); // If zebra image class is missing, include it!

function laborator_img($url, $width = 0, $height = 0, $crop = FALSE)
{
	$upload_dir	= wp_upload_dir();
	
	$post_thumbnail_url = '';
	
	$wpurl 		= site_url();
	$baseurl 	= $upload_dir['baseurl'];
	
	# Get Predefined Image Size
	if(is_string($width))
	{
		$image_size = LaboratorImageSizes::get_img_size($width);
		extract($image_size);
	}
	
	
	# Get from post ID
	if(is_numeric($url))
	{
		$post_thumbnail_id = get_post_thumbnail_id($url);
		
		if($post_thumbnail_id)
		{
			$post_thumbnail_url = wp_get_attachment_url($post_thumbnail_id);
		}
		else
		{
			return '';
		}
	}
	else
	{
		$post_thumbnail_url = $url;
	}
	
	
	# Verify if its on this server
	if(strpos($post_thumbnail_url, $wpurl) != -1)
	{
		$relative_path 	= str_replace($wpurl, '', $post_thumbnail_url);
		$relative_path 	= ltrim($relative_path, '/');
		$absolute_path 	= ABSPATH . $relative_path;
		
		$basename 		= basename($absolute_path);
		
		# New Image Name
		$thumbnail_name	= 'labimg_' . ($width ? "{$width}_" : '') . ($height ? "{$height}_" : '') . ($crop ? "1_" : '') . $basename;
		$thumbnail_path	= dirname($absolute_path) . '/' . $thumbnail_name;
		$thumbnail_url 	= dirname($post_thumbnail_url) . '/' . $thumbnail_name;
		
		# Check if cached
		if(file_exists($thumbnail_path))
		{
			return $thumbnail_url;
		}
		
		# Create File
		if(file_exists($absolute_path))
		{
			# Generate Img
			$img = new Zebra_Image();
			
			$img->source_path = $absolute_path;
			$img->target_path = $thumbnail_path;
			$img->enlarge_smaller_images = TRUE;
			$img->preserve_aspect_ratio = TRUE;
			
			if($crop)
				$img->resize($width, $height, ZEBRA_IMAGE_CROP_CENTER, '#FFF');
			else
				$img->resize($width, $height, ZEBRA_IMAGE_NOT_BOXED, '#FFF');
			
			return $thumbnail_url;
		}
	}
	
	return '';
}

function laborator_show_img($url, $width = 0, $height = 0, $crop = FALSE)
{
	$img_path = laborator_img($url, $width, $height, $crop);
	
	if($img_path)
	{
		return '<img src="' . $img_path . '" ' . (is_string($width) ? (' alt="' . $width . '"') : '') . ' />';
	}
}

function laborator_img_add_size($alias, $width = 0, $height = 0, $crop = FALSE)
{
	LaboratorImageSizes::add_img_size($alias, $width, $height, $crop);
}


/* Class to Hold Registered Laborator Image Sizes */
class LaboratorImageSizes 
{
	public static $image_sizes = array();
	
	public static function add_img_size($alias, $width = 0, $height = 0, $crop)
	{
		self::$image_sizes[$alias] = array('width' => $width, 'height' => $height, 'crop' => $crop ? TRUE : FALSE);
	}
	
	public static function get_img_size($alias)
	{
		return self::$image_sizes[$alias];
	}
}